package org.callisto.handlers;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observable;

import org.callisto.model.Event;
import org.callisto.model.Keyboard;

public class TCPOutputHandler extends KeyboardObserver {
	private static final int PORT = 8888;
	private static boolean connectionError = false;
	static Socket socket = null;
	static PrintWriter out = null;

	private Socket getSocket() {
		if (socket == null && connectionError == false) {
			try {
				ServerSocket serverSocket = new ServerSocket(PORT);
				System.out.println("Server listening on port " + PORT + "; blocked until connected");
				socket = serverSocket.accept();
				System.out.println("Connection accepted [port=" + socket.getPort() + ",lport=" +
						socket.getLocalPort() + ",address=" + socket.getInetAddress() + "]");
			} catch (Exception e) {
				System.out.println("Socket connection failed");
				e.getMessage();
				connectionError = true;
				
			}
		} 
		return socket;
	}

	public TCPOutputHandler(Keyboard keyboard) {
		super(keyboard);
		System.out.println("[TCP output handler]");
		socket = getSocket();		
		if (out==null && connectionError == false) {
			try {
				out = new PrintWriter(
			            new BufferedWriter(
			              new OutputStreamWriter(
			                socket.getOutputStream()
			              )
			            )
			            ,true
			          );
			} catch (Exception e) {
				e.printStackTrace();
			}		
		}
	}
	
	public void update(Observable o, Object message) {	
		out.println(message);
		out.flush();
	}

	@Override
	public void handleEvent(Event event) {
	}
}
